# coding: utf-8
# @Author : lryself
# @Date : 2020/12/14 17:30
# @Software: PyCharm
import datetime

from flask import current_app
from werkzeug.security import generate_password_hash

from ..models import db
from ..models.UserInfoModel import UserInfo
from ..utils import commons
from ..utils.response_code import RET


class UserInfoController(UserInfo):
    @classmethod
    def add(cls, **kwargs):
        user_name = kwargs.get('user_name')
        mail = kwargs.get('mail')
        password = kwargs.get('password') if kwargs.get('password') else '123456'
        user_type = kwargs.get('user_type') if kwargs.get('user_type') else '1'

        # 检查是否有重复的邮箱
        try:
            filter_list = []
            filter_list.append(cls.mail == mail)

            mail_model = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，获取信息失败', 'error': str(e)}

        if mail_model.first():
            return {'code': RET.DATAEXIST, 'msg': '账号邮箱已存在', 'error': "账号邮箱已存在"}

        user_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S')+str(datetime.datetime.now()).split(".")[1]
        # 生成用户id 插入信息到表里
        try:
            UserAccount = UserInfo(
                userID=user_id,
                userName=user_name,
                password=generate_password_hash(password),
                otherInfo=kwargs.get('otherInfo'),
                mail=mail,
                userType=user_type,
            )
            db.session.add(UserAccount)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，添加用户账号失败', 'error': str(e)}

        data = commons.query_to_dict(UserAccount)
        back_data = {
            'user_id': data.get('user_id'),
            'createTime': data.get('createTime')
        }

        return {'code': RET.OK, 'msg': '创建用户账户成功', 'data': back_data}

    @classmethod
    def get(cls, **kwargs):
        filter_list = []
        if kwargs.get('user_id'):
            filter_list.append(cls.userID == kwargs.get('user_id'))
        if kwargs.get('mail'):
            filter_list.append(cls.mail == kwargs.get('mail'))
        if kwargs.get('user_name'):
            filter_list.append(cls.mail.contains(kwargs.get('user_name')))
        try:
            user = db.session.query(cls).filter(*filter_list).first()
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，获取学生信息失败', 'error': str(e)}

        if not user:
            return {'code': RET.NODATA, 'msg': '无用户信息', 'error': '无用户信息'}

        return {"code": RET.OK, "msg": "查询成功！", "data": commons.query_to_dict(user)}
